#include "usedialog.h"
#include "ui_usedialog.h"
#include<QHBoxLayout>
#include<QComboBox>
#include<QListWidgetItem>
#include<QJsonObject>
#include<QJsonArray>
#include<QJsonDocument>
#include"src/mes.h"
#include<QScrollArea>
#include<QMessageBox>
#include<QDebug>

UseDialog::UseDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::UseDialog)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint);
    ui->checkWidget->setEnabled(false);
    ui->recheckWidget->setEnabled(false);
    ui->maintainWidget->setEnabled(false);
    checkList=Mes::getInstance()->getCheckItemList("check","checkIndex");
    recheckList=Mes::getInstance()->getCheckItemList("recheck","recheckIndex");
    maintainList=Mes::getInstance()->getCheckItemList("maintain","maintainIndex");
    this->resize( QSize( 545, 600));
}

UseDialog::UseDialog(QWidget *parent,int windowFlag,const QMap<QString,QVariant> &userMap) :
    QDialog(parent),
    ui(new Ui::UseDialog)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()&~Qt::WindowContextHelpButtonHint);
    checkList=Mes::getInstance()->getCheckItemList("check","checkIndex");
    recheckList=Mes::getInstance()->getCheckItemList("recheck","recheckIndex");
    maintainList=Mes::getInstance()->getCheckItemList("maintain","maintainIndex");
    this->resize( QSize( 545, 600));
    this->windowFlag=windowFlag;
    this->userMap=userMap;
    if(windowFlag==ADDITEMS){
        setWindowTitle(QString("正在为%1(%2)添加点检信息").arg(userMap["norms"].toString()).arg(userMap["NO"].toString()));
        initAddItems();
    }else if(windowFlag==CHANGEITEMS){
        setWindowTitle(QString("正在修改%1(%2)的点检信息").arg(userMap["norms"].toString()).arg(userMap["NO"].toString()));
        initChangeItems();
    }
}

void UseDialog::initAddItems()
{
    ui->checkWidget->setEnabled(false);
    ui->recheckWidget->setEnabled(false);
    ui->maintainWidget->setEnabled(false);
}

void UseDialog::initChangeItems()
{
    QMap<QString,QVariant> checkMap;
    QMap<QString,QVariant> recheckMap;
    QMap<QString,QVariant> maintainMap;
    if(Mes::getInstance()->getUserData(userMap,checkMap,recheckMap,maintainMap)){
        qDebug()<<"checkMap:"<<checkMap;
        qDebug()<<"recheckMap:"<<recheckMap;
        qDebug()<<"maintainMap:"<<maintainMap;
        if(!checkMap.isEmpty()){
            ui->checkBox->setCheckState(Qt::Checked);
            on_checkBox_stateChanged(0);
            QList<QList<QVariant>> list;
            if(!JsonToListList(checkMap["items"].toString(),list)) return;
            for(auto i=0;i<list.size();i++) {
                QHBoxLayout *tmpHlayout=new QHBoxLayout;
                QComboBox *tmpLineEdit=new QComboBox;
                tmpLineEdit->setEditable(true);
                tmpLineEdit->addItems(checkList);
                tmpLineEdit->setCurrentText(list[i][0].toString());
                QComboBox *tmpCombox=new QComboBox;
                tmpCombox->addItems(tmpStrList);
                tmpCombox->setCurrentIndex(list[i][1].toBool()?1:0);
                tmpHlayout->addWidget(tmpLineEdit);
                tmpHlayout->addWidget(tmpCombox);
                tmpHlayout->setStretch(0,4);
                tmpHlayout->setStretch(1,1);
                QWidget *tmpWidget=new QWidget;
                tmpWidget->setLayout(tmpHlayout);
                QListWidgetItem *item=new QListWidgetItem;
                item->setSizeHint(QSize(200,40));
                ui->checkListWidget->addItem(item);
                ui->checkListWidget->setItemWidget(item,tmpWidget);
                checkLineEditList<<tmpLineEdit->lineEdit();
                checkComboxList<<tmpCombox;
            }
            ui->checkNumber->setText(checkMap["checkWorkNumber"].toString());
            ui->checkTime->setTime(checkMap["noticeTime"].toTime());
            ui->checkCycle->setValue(checkMap["cycle"].toInt());
            on_checkNumber_textEdited(checkMap["checkWorkNumber"].toString());
        }else{
            ui->checkBox->setCheckState(Qt::Unchecked);
            ui->checkWidget->setEnabled(false);
        }

        if(!recheckMap.isEmpty()){
            ui->recheckBox->setCheckState(Qt::Checked);
            on_checkBox_stateChanged(0);
            QList<QList<QVariant>> list;
            if(!JsonToListList(recheckMap["items"].toString(),list)) return;
            for(auto i=0;i<list.size();i++) {
                QHBoxLayout *tmpHlayout=new QHBoxLayout;
                QComboBox *tmpLineEdit=new QComboBox;
                tmpLineEdit->setEditable(true);
                tmpLineEdit->addItems(recheckList);
                tmpLineEdit->setCurrentText(list[i][0].toString());
                QComboBox *tmpCombox=new QComboBox;
                tmpCombox->addItems(tmpStrList);
                tmpCombox->setCurrentIndex(list[i][1].toBool()?1:0);
                tmpHlayout->addWidget(tmpLineEdit);
                tmpHlayout->addWidget(tmpCombox);
                tmpHlayout->setStretch(0,4);
                tmpHlayout->setStretch(1,1);
                QWidget *tmpWidget=new QWidget;
                tmpWidget->setLayout(tmpHlayout);
                QListWidgetItem *item=new QListWidgetItem;
                item->setSizeHint(QSize(200,40));
                ui->recheckListWidget->addItem(item);
                ui->recheckListWidget->setItemWidget(item,tmpWidget);
                recheckLineEditList<<tmpLineEdit->lineEdit();
                recheckComboxList<<tmpCombox;
            }
            ui->recheckNumber->setText(recheckMap["checkWorkNumber"].toString());
            ui->recheckTime->setTime(recheckMap["noticeTime"].toTime());
            ui->recheckCycle->setValue(recheckMap["cycle"].toInt());
            on_recheckNumber_textEdited(recheckMap["checkWorkNumber"].toString());
        }else{
            ui->recheckBox->setCheckState(Qt::Unchecked);
            ui->recheckWidget->setEnabled(false);
        }

        if(!maintainMap.isEmpty()){
            ui->maintainBox->setCheckState(Qt::Checked);
            on_checkBox_stateChanged(0);
            QList<QList<QVariant>> list;
            if(!JsonToListList(maintainMap["items"].toString(),list)) return;
            for(auto i=0;i<list.size();i++) {
                QHBoxLayout *tmpHlayout=new QHBoxLayout;
                QComboBox *tmpLineEdit=new QComboBox;
                tmpLineEdit->setEditable(true);
                tmpLineEdit->addItems(maintainList);
                tmpLineEdit->setCurrentText(list[i][0].toString());
                QComboBox *tmpCombox=new QComboBox;
                tmpCombox->addItems(tmpStrList);
                tmpCombox->setCurrentIndex(list[i][1].toBool()?1:0);
                tmpHlayout->addWidget(tmpLineEdit);
                tmpHlayout->addWidget(tmpCombox);
                tmpHlayout->setStretch(0,4);
                tmpHlayout->setStretch(1,1);
                QWidget *tmpWidget=new QWidget;
                tmpWidget->setLayout(tmpHlayout);
                QListWidgetItem *item=new QListWidgetItem;
                item->setSizeHint(QSize(200,40));
                ui->maintainListWidget->addItem(item);
                ui->maintainListWidget->setItemWidget(item,tmpWidget);
                maintainLineEditList<<tmpLineEdit->lineEdit();
                maintainComboxList<<tmpCombox;
            }
            ui->maintainNumber->setText(maintainMap["checkWorkNumber"].toString());
            ui->maintainTime->setTime(maintainMap["noticeTime"].toTime());
            ui->maintainCycle->setValue(maintainMap["cycle"].toInt());
            on_maintainNumber_textEdited(maintainMap["checkWorkNumber"].toString());
        }else{
            ui->maintainBox->setCheckState(Qt::Unchecked);
            ui->maintainWidget->setEnabled(false);
        }
    }
}

UseDialog::~UseDialog()
{
    delete ui;
}

void UseDialog::on_checkBox_5_stateChanged(int arg1)
{
    ui->checkBox_5->setCheckState(Qt::Checked);
}

void UseDialog::on_checkBox_4_stateChanged(int arg1)
{
    ui->checkBox_4->setCheckState(Qt::Checked);
}

void UseDialog::on_checkBox_6_stateChanged(int arg1)
{
    ui->checkBox_6->setCheckState(Qt::Checked);
}

void UseDialog::on_checkBox_stateChanged(int arg1)
{
    if(ui->checkBox->checkState()==Qt::Checked){
        ui->checkWidget->setEnabled(true);
    }else{
        ui->checkWidget->setEnabled(false);
    }
}

void UseDialog::on_recheckBox_stateChanged(int arg1)
{
    if(ui->recheckBox->checkState()==Qt::Checked){
        ui->recheckWidget->setEnabled(true);
    }else{
        ui->recheckWidget->setEnabled(false);
    }
}

void UseDialog::on_maintainBox_stateChanged(int arg1)
{
    if(ui->maintainBox->checkState()==Qt::Checked){
        ui->maintainWidget->setEnabled(true);
    }else{
        ui->maintainWidget->setEnabled(false);
    }
}

bool UseDialog::orginConfirm()
{
    QList<QList<QVariant>> checkItemStatusList;
    QList<QList<QVariant>> recheckItemStatusList;
    QList<QList<QVariant>> maintainItemStatusList;
    if(ui->checkBox->checkState()==Qt::Unchecked && ui->recheckBox->checkState()==Qt::Unchecked &&
            ui->maintainBox->checkState()==Qt::Unchecked){
        QMessageBox::warning(this,QString("提示"),"点检信息不能全为空    ");
        return false;
    }

    if(ui->checkBox->checkState()==Qt::Checked){
        if(ui->checkNumber->text().trimmed()==""){
            ui->checkError->setText("带*号项目不能为空");
            QMessageBox::warning(this, QString("失败"), QString("带*号项目不能为空        "));
            return false;
        }

        int n=0;
        for(QLineEdit* i:checkLineEditList){
            QList<QVariant> tmpList;
            if(i->text().trimmed()==""){
                QMessageBox::warning(this, QString("失败"), QString("检查项目不能为空        "));
                return false;
            }else{
                tmpList<<i->text().trimmed()<<(checkComboxList[n]->currentIndex()==0?false:true);
            }
            checkItemStatusList<<tmpList;
            ++n;
        }

        if(checkItemStatusList.isEmpty()){
            ui->checkListError->setText("至少要有1个检查项目");
            QMessageBox::warning(this, QString("失败"), QString("至少要有1个检查项目        "));
            return false;
        }

        if(!Mes::getInstance()->workNumberIsExist(ui->checkNumber->text().trimmed())){
            ui->checkError->setText("该工号不存在");
            QMessageBox::warning(this, QString("失败"), QString("%1该工号不存在       ").arg(ui->checkNumber->text().trimmed()));
            return false;
        }

        checkMap.insert("threeModel","点检");
        checkMap.insert("noticeTime",ui->checkTime->time().toString("hh:mm"));
        checkMap.insert("cycle",ui->checkCycle->value());
        checkMap.insert("items",jsonToStr(checkItemStatusList));
        checkMap.insert("checkWorkNumber",ui->checkNumber->text().trimmed());
    }

    if(ui->recheckBox->checkState()==Qt::Checked){
        if(ui->recheckNumber->text().trimmed()==""){
            ui->recheckError->setText("带*号项目不能为空");
            QMessageBox::warning(this, QString("失败"), QString("带*号项目不能为空        "));
            return false;
        }

        int n=0;
        for(QLineEdit* i:recheckLineEditList){
            QList<QVariant> tmpList;
            if(i->text().trimmed()==""){
                QMessageBox::warning(this, QString("失败"), QString("检查项目不能为空        "));
                return false;
            }else{
                tmpList<<i->text().trimmed()<<(recheckComboxList[n]->currentIndex()==0?false:true);
            }
            recheckItemStatusList<<tmpList;
            ++n;
        }

        if(recheckItemStatusList.isEmpty()){
            ui->recheckListError->setText("至少要有1个检查项目");
            QMessageBox::warning(this, QString("失败"), QString("至少要有1个检查项目        "));
            return false;
        }

        if(!Mes::getInstance()->workNumberIsExist(ui->recheckNumber->text().trimmed())){
            ui->recheckError->setText("该工号不存在");
            QMessageBox::warning(this, QString("失败"), QString("%1该工号不存在       ").arg(ui->recheckNumber->text().trimmed()));
            return false;
        }

        recheckMap.insert("threeModel","校验");
        recheckMap.insert("noticeTime",ui->recheckTime->time().toString("hh:mm"));
        recheckMap.insert("cycle",ui->recheckCycle->value());
        recheckMap.insert("items",jsonToStr(recheckItemStatusList));
        recheckMap.insert("checkWorkNumber",ui->recheckNumber->text().trimmed());
    }

    if(ui->maintainBox->checkState()==Qt::Checked){
        if(ui->maintainNumber->text().trimmed()==""){
            ui->maintainError->setText("带*号项目不能为空");
            QMessageBox::warning(this, QString("失败"), QString("带*号项目不能为空        "));
            return false;
        }

        int n=0;
        for(QLineEdit* i:maintainLineEditList){
            QList<QVariant> tmpList;
            if(i->text().trimmed()==""){
                QMessageBox::warning(this, QString("失败"), QString("检查项目不能为空        "));
                return false;
            }else{
                tmpList<<i->text().trimmed()<<(maintainComboxList[n]->currentIndex()==0?false:true);
            }
            maintainItemStatusList<<tmpList;
            ++n;
        }

        if(maintainItemStatusList.isEmpty()){
            ui->maintainListError->setText("至少要有1个检查项目");
            QMessageBox::warning(this, QString("失败"), QString("至少要有1个检查项目        "));
            return false;
        }

        if(!Mes::getInstance()->workNumberIsExist(ui->maintainNumber->text().trimmed())){
            ui->maintainError->setText("该工号不存在");
            QMessageBox::warning(this, QString("失败"), QString("%1该工号不存在       ").arg(ui->maintainNumber->text().trimmed()));
            return false;
        }

        maintainMap.insert("threeModel","保养");
        maintainMap.insert("noticeTime",ui->maintainTime->time().toString("hh:mm"));
        maintainMap.insert("cycle",ui->maintainCycle->value());
        maintainMap.insert("items",jsonToStr(maintainItemStatusList));
        maintainMap.insert("checkWorkNumber",ui->maintainNumber->text().trimmed());
    }
}

void UseDialog::confirm()
{
    if(orginConfirm()){
        accept();
    }
}

void UseDialog::addConfirm()
{
    if(orginConfirm()){
        if(Mes::getInstance()->addUserForm(userMap,checkMap,recheckMap,maintainMap)){
            QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
            accept();
        }
    }
}

void UseDialog::changeConfirm()
{
    if(orginConfirm()){
        if(Mes::getInstance()->updateUserForm(userMap,checkMap,recheckMap,maintainMap)){
            QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
            accept();
        }
    }
}

void UseDialog::on_confirmButton_clicked()              // 提交
{
    switch (windowFlag) {
    case ORGIN:confirm();break;
    case ADDITEMS:addConfirm();break;
    case CHANGEITEMS:changeConfirm();break;
    }
}

//    checkLineEditList.clear();
//    checkComboxList.clear();
//    recheckLineEditList.clear();
//    recheckComboxList.clear();
//    maintainLineEditList.clear();
//    maintainComboxList.clear();

void UseDialog::on_pushButton_clicked()
{
    reject();
}

void UseDialog::on_pushButton_4_clicked()
{
    QHBoxLayout *tmpHlayout=new QHBoxLayout;
    QComboBox *tmpLineEdit=new QComboBox;
    tmpLineEdit->setEditable(true);
    tmpLineEdit->addItems(checkList);
    QComboBox *tmpCombox=new QComboBox;
    tmpCombox->addItems(tmpStrList);
    tmpHlayout->addWidget(tmpLineEdit);
    tmpHlayout->addWidget(tmpCombox);
    tmpHlayout->setStretch(0,4);
    tmpHlayout->setStretch(1,1);
    QWidget *tmpWidget=new QWidget;
    tmpWidget->setLayout(tmpHlayout);
//    if(tmpLineEdit->text().trimmed()!=""){
//        QList<QVariant> tmpStatusList{tmpLineEdit->text().trimmed(),tmpCombox->currentIndex()==0?false:true};
//        checkItemStatusList<<tmpStatusList;
//    }
    QListWidgetItem *item=new QListWidgetItem;
    item->setSizeHint(QSize(200,40));
    ui->checkListWidget->addItem(item);
    ui->checkListWidget->setItemWidget(item,tmpWidget);
    ui->checkListWidget->setFocus();
    ui->checkListWidget->setCurrentItem(item);
    tmpLineEdit->setFocus();
    tmpLineEdit->lineEdit()->selectAll();
//    QList<QWidget*> tmpList;
//    tmpList<<tmpLineEdit<<tmpCombox;
    checkLineEditList<<tmpLineEdit->lineEdit();
    checkComboxList<<tmpCombox;
}

void UseDialog::on_pushButton_5_clicked()
{
    int row=ui->checkListWidget->currentRow();
    ui->checkListWidget->takeItem(row);
//    checkItemStatusList.removeAt(row);
    checkLineEditList.removeAt(row);
    checkComboxList.removeAt(row);
}

void UseDialog::on_pushButton_2_clicked()
{
    QHBoxLayout *tmpHlayout=new QHBoxLayout;
    QComboBox *tmpLineEdit=new QComboBox;
    tmpLineEdit->setEditable(true);
    tmpLineEdit->addItems(recheckList);
    QComboBox *tmpCombox=new QComboBox;
    tmpCombox->addItems(tmpStrList);
    tmpHlayout->addWidget(tmpLineEdit);
    tmpHlayout->addWidget(tmpCombox);
    tmpHlayout->setStretch(0,4);
    tmpHlayout->setStretch(1,1);
    QWidget *tmpWidget=new QWidget;
    tmpWidget->setLayout(tmpHlayout);
//    if(tmpLineEdit->text().trimmed()!=""){
//        QList<QVariant> tmpStatusList{tmpLineEdit->text().trimmed(),tmpCombox->currentIndex()==0?false:true};
//        recheckItemStatusList<<tmpStatusList;
//    }
    QListWidgetItem *item=new QListWidgetItem;
    item->setSizeHint(QSize(200,40));
    ui->recheckListWidget->addItem(item);
    ui->recheckListWidget->setItemWidget(item,tmpWidget);
    ui->recheckListWidget->setFocus();
    ui->recheckListWidget->setCurrentItem(item);
    tmpLineEdit->setFocus();
    tmpLineEdit->lineEdit()->selectAll();
    recheckLineEditList<<tmpLineEdit->lineEdit();
    recheckComboxList<<tmpCombox;
}

void UseDialog::on_pushButton_3_clicked()
{
    int row=ui->recheckListWidget->currentRow();
    ui->recheckListWidget->takeItem(row);
//    recheckItemStatusList.removeAt(row);
    recheckLineEditList.removeAt(row);
    recheckComboxList.removeAt(row);
}

void UseDialog::on_pushButton_7_clicked()
{
    QHBoxLayout *tmpHlayout=new QHBoxLayout;
    QComboBox *tmpLineEdit=new QComboBox;
    tmpLineEdit->setEditable(true);
    tmpLineEdit->addItems(maintainList);
    QComboBox *tmpCombox=new QComboBox;
    tmpCombox->addItems(tmpStrList);
    tmpHlayout->addWidget(tmpLineEdit);
    tmpHlayout->addWidget(tmpCombox);
    tmpHlayout->setStretch(0,4);
    tmpHlayout->setStretch(1,1);
    QWidget *tmpWidget=new QWidget;
    tmpWidget->setLayout(tmpHlayout);
//    if(tmpLineEdit->text().trimmed()!=""){           // 需要填值，返回true;
//        QList<QVariant> tmpStatusList{tmpLineEdit->text().trimmed(),tmpCombox->currentIndex()==0?false:true};
//        maintainItemStatusList<<tmpStatusList;
//    }
    QListWidgetItem *item=new QListWidgetItem;
    item->setSizeHint(QSize(200,40));
    ui->maintainListWidget->addItem(item);
    ui->maintainListWidget->setItemWidget(item,tmpWidget);
    ui->maintainListWidget->setFocus();
    ui->maintainListWidget->setCurrentItem(item);
    tmpLineEdit->setFocus();
    tmpLineEdit->lineEdit()->selectAll();
    maintainLineEditList<<tmpLineEdit->lineEdit();
    maintainComboxList<<tmpCombox;
}

void UseDialog::on_pushButton_6_clicked()
{
    int row=ui->maintainListWidget->currentRow();
    ui->maintainListWidget->takeItem(row);
//    maintainItemStatusList.removeAt(row);
    maintainLineEditList.removeAt(row);
    maintainComboxList.removeAt(row);
}

QString UseDialog::jsonToStr(QList<QList<QVariant>>& list)
{
    QJsonArray json_array;
    for (qint32 i = 0; i < list.size(); ++i) {
        QList<QVariant> temp_list = list.at(i);
        QJsonArray temp_array;
        for (qint32 j = 0; j < temp_list.size(); ++j) {
            if(j==0){
                temp_array.append(temp_list.at(j).toString());continue;
            }
            if(j==1){
                temp_array.append(temp_list.at(j).toBool());continue;
            }
        }
        json_array.append(temp_array);
    }
    QJsonDocument parse_doucment(json_array);
    QString msg = parse_doucment.toJson(QJsonDocument::Compact);
    return msg;
}

void UseDialog::on_checkNumber_textEdited(const QString &arg1)
{
    QString name;
    if(Mes::getInstance()->getName(arg1,name)){
        ui->checkError->setText(name);
    }else{
        ui->checkError->setText("工号不存在");
    }
}

void UseDialog::on_recheckNumber_textEdited(const QString &arg1)
{
    QString name;
    if(Mes::getInstance()->getName(arg1,name)){
        ui->recheckError->setText(name);
    }else{
        ui->recheckError->setText("工号不存在");
    }
}

void UseDialog::on_maintainNumber_textEdited(const QString &arg1)
{
    QString name;
    if(Mes::getInstance()->getName(arg1,name)){
        ui->maintainError->setText(name);
    }else{
        ui->maintainError->setText("工号不存在");
    }
}

bool UseDialog::JsonToListList(const QString &msg, QList<QList<QVariant>> &list)
{
    QJsonParseError json_error;
    QJsonDocument parse_document = QJsonDocument::fromJson(msg.toUtf8(), &json_error);
    if (json_error.error == QJsonParseError::NoError) {
        if (parse_document.isArray()) {
            QJsonArray json_array1 = parse_document.array();
            qint32 size = json_array1.size();
            for (qint32 i = 0; i < size; ++i) {
                QList<QVariant> temp_list;
                QJsonArray json_array2 = json_array1.at(i).toArray();
                for (qint32 j = 0; j < json_array2.size(); ++j) {
                    temp_list.append(json_array2.at(j).toVariant());
                }
                list.append(temp_list);
            }
            return true;
        } else {
            qWarning() << "the json is not array error! "
                       "jsonError:" << json_error.error;
            return false;
        }
    } else {
        qWarning() << "the json analysisError! "
                   "jsonError:" << json_error.error;
        return false;
    }
}
